package com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import android.widget.ListPopupWindow
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityShedRacePigeonPairBinding
import com.gexiaobao.pigeon.ui.activity.LoginActivity
import com.gexiaobao.pigeon.ui.adapter.MyAdapter
import com.gexiaobao.pigeon.ui.adapter.PigeonShedListAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.ShedPigeonViewModel
import com.kingja.loadsir.core.LoadService
import com.yanzhenjie.recyclerview.OnItemMenuClickListener
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import me.hgj.jetpackmvvm.ext.lifecycle.KtxActivityManger
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity

/**
 * @Author      : hxw
 * @Date        : 2024/4/17 8:58
 * @Describe    : 公棚收鸽（公棚下所有赛鸽列表）
 */
class ActivityCollectPigeons : BaseActivity<ShedPigeonViewModel, ActivityShedRacePigeonPairBinding>() {

    private lateinit var loadsir: LoadService<Any>
    private val mAdapter: PigeonShedListAdapter by lazy { PigeonShedListAdapter(arrayListOf()) }
    private var mRaceId = 0
    private var ringId = ""
    private var memberName = ""
    private var listPopupWindow: ListPopupWindow? = null
    private val mList: MutableList<String> = mutableListOf()
    private var mSearchType = ""
    private var loftPicIs = 0
    private var ringSnIs = 0
    override fun initView(savedInstanceState: Bundle?) {
        mSearchType = getString(R.string.search_by_ringId)
        mDatabind.includeBar.toolbar.initClose(getString(R.string.pigeon_list)) {
            finish()
        }
        mRaceId = intent.getIntExtra("raceId", 0)
        mDatabind.mButtonAll.isSelected = true
        mDatabind.includeSearch.tvSearchType.text = mSearchType
        initPopup()

        val swipeMenuCreator = SwipeMenuCreator { _, rightMenu, _ ->
            val width = resources.getDimensionPixelSize(R.dimen.dp_70)
            val height = ViewGroup.LayoutParams.MATCH_PARENT
            val deleteItem = SwipeMenuItem(this)
                .setBackground(R.drawable.round_b_g_5_train_fly_list_delete_red)
                .setTextColor(Color.WHITE)
                .setText(R.string.delete)
                .setTextSize(15)
                .setWidth(width)
                .setHeight(height)
            rightMenu.addMenuItem(deleteItem)
        }
        mDatabind.layoutList.swipeRecyclerView.setSwipeMenuCreator(swipeMenuCreator)

        val mItemMenuClickListener = OnItemMenuClickListener { menuBridge, position ->
            /** 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱 */
            menuBridge.closeMenu()
            /** 调用删除接口 */
            showDeleteDialog(mAdapter.data[position].id)
        }
        mDatabind.layoutList.swipeRecyclerView.setOnItemMenuClickListener(mItemMenuClickListener)

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(this), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(this, 0f)))
            it.initFooter {
                mViewModel.getLoftPigeonList(false, memberName, ringId, mRaceId, loftPicIs, ringSnIs)
            }
        }

        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRefreshLayout) {
            //点击重试时触发的操作
            onRefresh(true)
        }

        mDatabind.layoutList.swipeRefreshLayout.init {
            onRefresh(true)
        }
        onRefresh(true)

        val startActivity = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.data != null && it.resultCode == Activity.RESULT_OK) {
                onRefresh(true)
            }
        }

        mAdapter.addChildClickViewIds(R.id.tv_shed_pair)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tv_shed_pair -> {
                    val intent = Intent(this, ActivityShedPigeonPair::class.java)
                    intent.putExtra("pigeonId", mAdapter.data[position].id)
                    startActivity.launch(intent)
                }
            }
        }

        mDatabind.includeSearch.editQuery.addTextChangedListener {
            mDatabind.includeSearch.ivClose.isVisible = it.toString().isNotEmpty()
        }

        mDatabind.includeSearch.editQuery.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH -> {
                    searchPigeon()
                    hideSoftKeyboard(this)
                }

                else -> {}
            }
            false
        }

        listPopupWindow?.setOnItemClickListener { _, _, position, _ ->
            mSearchType = mList[position]
            mDatabind.includeSearch.tvSearchType.text = mSearchType
            mList.add(0, mList.removeAt(position))
            listPopupWindow!!.dismiss()
        }
    }

    private fun showDeleteDialog(id: Int) {
        val dialog = RxDialogDefault(this)
        dialog.setContent(getString(R.string.is_remove_this_pigeon))
        dialog.setSureListener {
            deleteShedPigeon(id)
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun initPopup() {
        mList.add(getString(R.string.search_by_foster))
        mList.add(getString(R.string.search_by_ringId))//"搜足环"

        /** 初始化ListPopupWindow，适配 */
        listPopupWindow = ListPopupWindow(this)
        val adapter = MyAdapter(this, mList)
        listPopupWindow?.setAdapter(adapter)
        listPopupWindow?.anchorView = mDatabind.includeSearch.llSearchType//设置ListPopupWindow的锚点，关联mButton位置
        listPopupWindow?.width = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow?.height = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow?.isModal = true
    }

    private fun deleteShedPigeon(id: Int) {
        showLoading(getString(R.string.loading))
        mViewModel.deleteLoftPigeon(id.toString())
    }

    private fun onRefresh(isRefresh: Boolean) {
        loadsir.showLoading()
        mViewModel.getLoftPigeonList(isRefresh, memberName, ringId, mRaceId, loftPicIs, ringSnIs)
    }

    override fun createObserver() {
        super.createObserver()
        /** 删除赛鸽 */
        mViewModel.deleteLoftPigeonResult.observe(this) {
            if (it.isSuccess) {
                onRefresh(true)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 退出 */
        mViewModel.logOutResult.observe(this) {
            if (it.isSuccess) {
                CacheUtil.setIsLogin(false)
                KtxActivityManger.finishAllActivity()
                startActivity<LoginActivity>()
                //带点渐变动画
                this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 获取公棚下赛鸽 */
        mViewModel.pigeonListResult.observe(this) {
            mDatabind.tvShedPigeonTotalNo.text = it.total.toString()
            loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeSearch.tvSearch,
            mDatabind.includeSearch.ivClose,
            mDatabind.includeSearch.llSearchType,
            mDatabind.mButtonAll,
            mDatabind.mButtonNoCamera,
            mDatabind.mButtonNoPair
        ) {
            when (it) {
                mDatabind.mButtonNoPair -> {
                    mDatabind.mButtonAll.isSelected = false
                    mDatabind.mButtonNoCamera.isSelected = false
                    mDatabind.mButtonNoPair.isSelected = true
                    loftPicIs = 0
                    ringSnIs = 2
                    onRefresh(true)
                }

                mDatabind.mButtonNoCamera -> {
                    mDatabind.mButtonAll.isSelected = false
                    mDatabind.mButtonNoCamera.isSelected = true
                    mDatabind.mButtonNoPair.isSelected = false
                    loftPicIs = 2
                    ringSnIs = 0
                    onRefresh(true)
                }

                mDatabind.mButtonAll -> {
                    mDatabind.mButtonAll.isSelected = true
                    mDatabind.mButtonNoCamera.isSelected = false
                    mDatabind.mButtonNoPair.isSelected = false
                    loftPicIs = 0
                    ringSnIs = 0
                    onRefresh(true)
                }

                mDatabind.includeSearch.llSearchType -> {
                    listPopupWindow?.show()
                }

                mDatabind.includeSearch.ivClose -> {
                    mDatabind.includeSearch.editQuery.setText("")
                    memberName = ""
                    ringId = ""
                    searchPigeon()
                }

                mDatabind.includeSearch.tvSearch -> {
                    searchPigeon()
                }
            }
        }
    }

    private fun searchPigeon() {
        if (mSearchType == "搜鸽主") {
            memberName = mDatabind.includeSearch.editQuery.text.toString().trim()
            ringId = ""
        } else {
            ringId = mDatabind.includeSearch.editQuery.text.toString().trim()
            memberName = ""
        }
        onRefresh(true)
    }
}